//
//  BridgeHelp.m
//  web-app
//
//  Created by 黄晓容 on 16/5/27.
//  Copyright © 2016年 cloud. All rights reserved.
//

#import "BridgeHelp.h"

#import <JavaScriptCore/JavaScriptCore.h>

#import "PhotoModel.h"

#import "UIView+ViewController.h"

#import "ViewController.h"

@protocol JSObjcDelegate <JSExport>

- (void)clickCamera:(NSDictionary *)json;

@end

@interface BridgeHelp() <JSObjcDelegate>

@property (nonatomic,strong) JSContext *jsContext;

@property (nonatomic,strong) ViewController *superViewController;

@end

// 桥接  使oc和js可以互相调用
@implementation BridgeHelp

- (instancetype)initWithWebView:(UIWebView *)webView
{
    if (self = [super init]) {
        self.superViewController = (ViewController *)webView.viewController;
        [self buildJSContext:webView];
    }
    return self;
}

- (void)buildJSContext:(UIWebView *)webView
{
    _jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    _jsContext[@"hxr"] = self;
    
    _jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
        context.exception = exceptionValue;
        NSLog(@"error：%@", exceptionValue);
    };
}

- (void)clickCamera:(NSDictionary *)json
{
    CGFloat height = [json[@"height"] floatValue];
    CGFloat width = [json[@"width"] floatValue];
    
    if (![self isPureNumandCharacters:json[@"height"]] || ![self isPureNumandCharacters:json[@"width"]] || height<=0 || width <=0) {
        [self showMsg:@"裁剪的高和宽必须都为正整数!"];
        return;
    }
    
    CameraType cameraType = [self handleCameraType:json[@"cameraType"]];
    UIImagePickerControllerSourceType photoSrouce = [self handlePhotoSource:json[@"photoSource"]];
    
    PhotoModel *photoModel = [[PhotoModel alloc] initWithHeight:height andWidth:width andCameraType:cameraType andPhotoSource:photoSrouce];
    
    [self.superViewController startCapture:photoModel];
}

- (CameraType)handleCameraType:(NSString *)type
{
    CameraType cameraType = CameraTypePostposition;
    if([type isEqualToString:@"preposition"]){
        cameraType = CameraTypePreposition;
    }
    return cameraType;
}

- (UIImagePickerControllerSourceType)handlePhotoSource:(NSString *)source
{
    UIImagePickerControllerSourceType photoSource = UIImagePickerControllerSourceTypeCamera;
    if ([source isEqualToString:@"photos"]) {
        photoSource = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }else if([source isEqualToString:@"all"]){
        photoSource = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    return photoSource;
}

- (void)showImage:(UIImage *)image
{
    NSArray<NSString *> *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *imageName = [NSString stringWithFormat:@"image%u.png",arc4random()];
    NSString *url = [[paths firstObject] stringByAppendingPathComponent:imageName];
    NSData *data = UIImagePNGRepresentation(image);
    
    [data writeToFile:url atomically:YES];
    
    NSString *js = [NSString stringWithFormat:@"showImage('%@')",url];
    [_jsContext evaluateScript:js];
    
    [self showMsg:@""];     //图片显示成功的情况下不显示警告信息
}

- (void)showMsg:(NSString *)msg
{
    NSString *js = [NSString stringWithFormat:@"showMsg('%@')",msg];
    [_jsContext evaluateScript:js];
}

#pragma mark - tool
- (BOOL)isPureNumandCharacters:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return YES;
}

@end
